import zstandard as zstd
from shared.crypto import AESCipher

class FullBackupEngine:
    def __init__(self, graph_client, storage):
        self.client = graph_client
        self.storage = storage
        self.cipher = AESCipher()
        
    def backup_mailbox(self, user_id: str):
        """执行邮箱全量备份"""
        # 获取所有邮件项
        messages = self._get_all_messages(user_id)
        
        # 处理邮件数据
        processed_data = self._process_messages(messages)
        
        # 压缩加密
        compressed = self._compress_data(processed_data)
        encrypted = self.cipher.encrypt(compressed)
        
        # 存储备份
        backup_id = self.storage.store(f"full_{user_id}", encrypted)
        return backup_id
        
    def _get_all_messages(self, user_id: str):
        """获取邮箱所有邮件"""
        return self.client.paginate(f"users/{user_id}/messages?$top=1000")
    
    def _process_messages(self, messages):
        """转换邮件格式"""
        return [{
            "id": msg["id"],
            "subject": msg.get("subject"),
            "body": msg.get("body", {}).get("content"),
            "received": msg["receivedDateTime"],
            "attachments": self._process_attachments(msg.get("attachments", []))
        } for msg in messages]
    
    def _compress_data(self, data):
        """Zstandard压缩"""
        cctx = zstd.ZstdCompressor()
        return cctx.compress(json.dumps(data).encode())